package com.seeyon.apps.relocationData.event;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.collaboration.event.CollaborationCancelEvent;
import com.seeyon.apps.collaboration.event.CollaborationProcessEvent;
import com.seeyon.apps.collaboration.event.CollaborationStopEvent;
import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.relocationData.utils.FormUtils;
import com.seeyon.apps.relocationData.utils.RelocationUtils;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.event.EventTriggerMode;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.annotation.ListenEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class RelocationListenerEvent {
    private static final Log log = LogFactory.getLog(RelocationListenerEvent.class);
    private FormApi4Cap4 cap4FormManager = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
    private static final String relocationCode = AppContext.getSystemProperty("relocationData.relocationCode");
    private static final String scheduleArchiveCode = AppContext.getSystemProperty("ebsRc.scheduleArchiveCode");
    private EnumManager enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew");
    private OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);

    private ColManager colManager ;
    public ColManager getColManager() {
        return colManager;
    }

    public void setColManager(ColManager colManager) {
        this.colManager = colManager;
    }

    /**
    * 功能:终止
    * @Date: 2025/1/24
    */
    @ListenEvent(event = CollaborationStopEvent.class,mode = EventTriggerMode.afterCommit)
    public void onCollaborationStop(CollaborationStopEvent event){
        try {
            ColSummary summary =colManager.getSummaryById(event.getSummaryId());
            FormBean form = cap4FormManager.getForm(summary.getFormAppid(), true);
            String nowTableName = form.getMasterTableBean().getTableName();
            FormBean formBean = cap4FormManager.getFormByFormCode(relocationCode);
            String tableName = formBean.getMasterTableBean().getTableName();
            FormBean scheduleArchiveForm = cap4FormManager.getFormByFormCode(scheduleArchiveCode);
            if (tableName.equals(nowTableName)){
                FormFieldBean nameBean = scheduleArchiveForm.getFieldBeanByDisplay("姓名");
                FormFieldBean typeBean = scheduleArchiveForm.getFieldBeanByDisplay("类型");
                FormFieldBean startDateBean = scheduleArchiveForm.getFieldBeanByDisplay("开始日期");
                FormFieldBean endDateBean = scheduleArchiveForm.getFieldBeanByDisplay("结束日期");
                FormFieldBean fqDateBean = scheduleArchiveForm.getFieldBeanByDisplay("发起时间");
                FormFieldBean wybsBean = scheduleArchiveForm.getFieldBeanByDisplay("唯一标识");

                //编号
                FormFieldBean codeBean = formBean.getFieldBeanByDisplay("NO");

                Long formRecordid = summary.getFormRecordid();
                FormDataMasterBean masterData = cap4FormManager.getDataMasterBeanById(formRecordid, formBean, null);
                String codeValue = String.valueOf(masterData.getFieldValue(codeBean.getName()));

                JSONObject dataJson = new JSONObject();
                dataJson.put("no",codeValue);
                RelocationUtils.delRelocationData(dataJson);
            }
        }catch (Exception e){
            log.error("动迁档案终止更新监听-CollaborationStopEvent error",e);
        }
    }
    /**
    * 功能:撤销
    * @Date: 2025/1/24
    */
    @ListenEvent(event = CollaborationCancelEvent.class,mode = EventTriggerMode.afterCommit)
    public void CollaborationCancel(CollaborationCancelEvent event){
        try {
            ColSummary summary =colManager.getSummaryById(event.getSummaryId());
            FormBean form = cap4FormManager.getForm(summary.getFormAppid(), true);
            String nowTableName = form.getMasterTableBean().getTableName();
            FormBean formBean = cap4FormManager.getFormByFormCode(relocationCode);
            String tableName = formBean.getMasterTableBean().getTableName();
            FormBean scheduleArchiveForm = cap4FormManager.getFormByFormCode(scheduleArchiveCode);
            if (tableName.equals(nowTableName)){
                FormFieldBean nameBean = scheduleArchiveForm.getFieldBeanByDisplay("姓名");
                FormFieldBean typeBean = scheduleArchiveForm.getFieldBeanByDisplay("类型");
                FormFieldBean startDateBean = scheduleArchiveForm.getFieldBeanByDisplay("开始日期");
                FormFieldBean endDateBean = scheduleArchiveForm.getFieldBeanByDisplay("结束日期");
                FormFieldBean fqDateBean = scheduleArchiveForm.getFieldBeanByDisplay("发起时间");
                FormFieldBean wybsBean = scheduleArchiveForm.getFieldBeanByDisplay("唯一标识");

                //编号
                FormFieldBean codeBean = formBean.getFieldBeanByDisplay("NO");

                Long formRecordid = summary.getFormRecordid();
                FormDataMasterBean masterData = cap4FormManager.getDataMasterBeanById(formRecordid, formBean, null);
                String codeValue = String.valueOf(masterData.getFieldValue(codeBean.getName()));

                JSONObject dataJson = new JSONObject();
                dataJson.put("no",codeValue);
                RelocationUtils.delRelocationData(dataJson);
            }
        }catch (Exception e){
            log.error("动迁档案撤销更新监听-CollaborationCancelEvent error",e);
        }
    }

    @ListenEvent(event= CollaborationProcessEvent.class,mode= EventTriggerMode.afterCommit)//协同发起成功提交事务后执行，异步模式。
    public void onCollaborationProcess(CollaborationProcessEvent event) throws BusinessException, SQLException, ParseException {
        String nodePolicy = event.getAffair().getNodePolicy();//动迁
        ColSummary summary =colManager.getSummaryById(event.getSummaryId());
        FormBean form = cap4FormManager.getForm(summary.getFormAppid(), true);
        String nowTableName = form.getMasterTableBean().getTableName();
        FormBean formBean = cap4FormManager.getFormByFormCode(relocationCode);
        String tableName = formBean.getMasterTableBean().getTableName();
        FormBean scheduleArchiveForm = cap4FormManager.getFormByFormCode(scheduleArchiveCode);
        if (tableName.equals(nowTableName) && nodePolicy.equals("动迁")){
            FormFieldBean nameBean = scheduleArchiveForm.getFieldBeanByDisplay("姓名");
            FormFieldBean typeBean = scheduleArchiveForm.getFieldBeanByDisplay("类型");
            FormFieldBean startDateBean = scheduleArchiveForm.getFieldBeanByDisplay("开始日期");
            FormFieldBean endDateBean = scheduleArchiveForm.getFieldBeanByDisplay("结束日期");
            FormFieldBean fqDateBean = scheduleArchiveForm.getFieldBeanByDisplay("发起时间");
            FormFieldBean wybsBean = scheduleArchiveForm.getFieldBeanByDisplay("唯一标识");
            //在岗开始时间
            FormFieldBean startdateBean = formBean.getFieldBeanByDisplay("Startdate");
            //在岗离开时间
            FormFieldBean enddateBean = formBean.getFieldBeanByDisplay("Enddate");
            //休假开始时间
            FormFieldBean departuredateBean = formBean.getFieldBeanByDisplay("Departuredate");
            //休假结束时间
            FormFieldBean returndateBean = formBean.getFieldBeanByDisplay("Returndate");
            //出差开始时间
            FormFieldBean departuredateTripBean = formBean.getFieldBeanByDisplay("DeparturedateTrip");
            //出差结束时间
            FormFieldBean returndateTripBean = formBean.getFieldBeanByDisplay("ReturndateTrip");
            //编号
            FormFieldBean codeBean = formBean.getFieldBeanByDisplay("NO");
            //人员名称
            FormFieldBean tripNameBean = formBean.getFieldBeanByDisplay("Name");
            //出差类型 国际出差 伊拉克境内出差
            FormFieldBean tripBean = formBean.getFieldBeanByDisplay("trip");

            Long formRecordid = summary.getFormRecordid();
            FormDataMasterBean masterData = cap4FormManager.getDataMasterBeanById(formRecordid, formBean, null);
            String codeValue = String.valueOf(masterData.getFieldValue(codeBean.getName()));
            Long nameValue = Long.parseLong(String.valueOf(masterData.getFieldValue(tripNameBean.getName())));
            V3xOrgMember member = orgManager.getMemberById(nameValue);
            Long memberId = member.getId();
            Object startDateObjectValue = masterData.getFieldValue(startdateBean.getName());
            Object enddateObjectValue = masterData.getFieldValue(enddateBean.getName());
            Object departuredateObjectValue = masterData.getFieldValue(departuredateBean.getName());
            Object returndateObjectValue = masterData.getFieldValue(returndateBean.getName());
            Object departuredateTripObjectValue = masterData.getFieldValue(departuredateTripBean.getName());
            Object returndateTripObjectValue = masterData.getFieldValue(returndateTripBean.getName());
            if (startDateObjectValue!=null&&enddateObjectValue != null){
                String startDate = sdf.format(sdf1.parse(String.valueOf(startDateObjectValue)));
                String endDate = sdf.format(sdf1.parse(String.valueOf(enddateObjectValue)));
                //创建类型为在岗
                JSONObject bodyJson = new JSONObject();
                bodyJson.put("wybs",codeValue+"-"+member.getName()+"-在岗");
                bodyJson.put("startDate", startDate);
                bodyJson.put("createDate", masterData.getStartDate());
                bodyJson.put("endDate", endDate);
                bodyJson.put("codeValue", codeValue);
                bodyJson.put("type", "在岗");
                bodyJson.put("memberId", memberId);
                // JSONObject jsonObject = RelocationUtils.addNewRelocationData(bodyJson);
                // JSONObject jsonObject1 = FormUtils.initiatingForm(jsonObject);
                log.info("创建在岗数据成功");
            }
            if (departuredateObjectValue!=null&&returndateObjectValue != null){
                String startDate = sdf.format(sdf1.parse(String.valueOf(departuredateObjectValue)));
                String endDate = sdf.format(sdf1.parse(String.valueOf(returndateObjectValue)));
                //休假 开始时间+2 结束时间-1
                String start2Data = this.getDateAfterTwoDays(startDate, 2);
                String end2Date = this.getDateAfterTwoDays(endDate, -1);
                //创建类型为休假
                JSONObject bodyJson = new JSONObject();
                bodyJson.put("wybs",codeValue+"-"+member.getName()+"-休假");
                bodyJson.put("startDate", start2Data);
                bodyJson.put("createDate", masterData.getStartDate());
                bodyJson.put("endDate", end2Date);
                bodyJson.put("codeValue", codeValue);
                bodyJson.put("type", "休假");
                bodyJson.put("memberId", memberId);
                JSONObject jsonObject = RelocationUtils.addNewRelocationData(bodyJson);
                FormUtils.initiatingForm(jsonObject);
            }
            if (departuredateTripObjectValue!=null&&returndateTripObjectValue != null){
                Object tripObj = masterData.getFieldValue(tripBean.getName());
                String startDate = sdf.format(sdf1.parse(String.valueOf(departuredateTripObjectValue)));
                String endDate = sdf.format(sdf1.parse(String.valueOf(returndateTripObjectValue)));
                //创建类型为出差
                JSONObject bodyJson = new JSONObject();
                bodyJson.put("wybs",codeValue+"-"+member.getName()+"-出差");
                bodyJson.put("startDate", startDate);
                bodyJson.put("createDate", masterData.getStartDate());
                bodyJson.put("endDate", endDate);
                bodyJson.put("codeValue", codeValue);
                bodyJson.put("type", "出差");
                bodyJson.put("memberId", memberId);
                if (tripObj!=null && !"".equals(tripObj)){
                    CtpEnumItem cacheTripItem = enumManagerNew.getCacheEnumItem(Long.valueOf(tripObj.toString()));
                    if (cacheTripItem!=null){
                        bodyJson.put("trip", cacheTripItem.getLabel());
                    }
                }
                JSONObject jsonObject = RelocationUtils.addNewRelocationData(bodyJson);
                FormUtils.initiatingForm(jsonObject);
            }

        }

    }

    /**
     * 获取指定日期的后两天
     * @param dateStr 输入日期字符串，格式为yyyy-MM-dd
     * @return 后两天的日期字符串，格式为yyyy-MM-dd
     */
    public static String getDateAfterTwoDays(String dateStr,long days) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 解析输入日期
        LocalDate date = LocalDate.parse(dateStr, formatter);

        // 计算后两天的日期
        LocalDate dateAfterTwoDays = date.plusDays(days);

        // 格式化输出
        return dateAfterTwoDays.format(formatter);
    }
}
